<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--组织数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入组织名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="deptOptionsShow" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" :default-expanded-keys="[deptOptionsShow[0].id]" accordion highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--用户数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="环保编号" prop="code">
                <el-input
                  v-model="queryParams.code"
                  placeholder="请输入环保编号"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="车牌号" prop="carNo">
                <el-input
                  v-model="queryParams.carNo"
                  placeholder="请输入车牌号"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="车辆类型" prop="carType">
                <el-cascader
                  ref="cascader"
                  v-model="queryParams.carType"
                  :options="carTypeOptions"
                  :props="{ value: 'id', label: 'label' }"
                  @change="queryCarTypeHandleChange"
                  @keyup.enter.native="handleQuery"></el-cascader>
              </el-form-item>
              <el-form-item label="车辆品牌" prop="carBrand">
                <el-select v-model="queryParams.carBrand" @focus="queryBrandOptions" @change="queryBrandSelected" filterable placeholder="请选择车辆品牌">
                  <el-option
                    v-for="item in carBrandOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="车辆型号" prop="carModel">
                <el-select v-model="queryParams.carModel" @focus="queryModelOptions" filterable placeholder="请选择车辆型号">
                  <el-option
                    v-for="item in carModelOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="其他类型" prop="otherType">
                <el-select v-model="queryParams.otherType" placeholder="请选择其他类型" clearable>
                  <el-option
                    v-for="dict in dict.type.dev_other_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPermi="['base:car:add']"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['base:car:edit']"
                >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['base:car:remove']"
                >删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport"
                  v-hasPermi="['base:car:export']"
                >导出</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="carList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="环保编号"  prop="code" width="120" :show-overflow-tooltip="true" />
              <el-table-column label="车牌号"  prop="carNo" />
              <el-table-column label="归属企业/人"  prop="ownerName" width="120" :show-overflow-tooltip="true" />
              <el-table-column label="联系方式"  prop="ownerContact" width="110" :show-overflow-tooltip="true" />
              <el-table-column label="车辆类型"  prop="carTypeName" width="160" :show-overflow-tooltip="true" />
              <el-table-column label="车辆品牌"  prop="carBrandName" width="80" :show-overflow-tooltip="true" />
              <el-table-column label="车辆型号"  prop="carModelName" width="150" :show-overflow-tooltip="true" />
              <el-table-column label="其他类型"  prop="otherType">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.dev_other_type" :value="scope.row.otherType"/>
                </template>
              </el-table-column>
              <el-table-column label="燃料类型"  prop="fuelType">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.base_fuel_type" :value="scope.row.fuelType"/>
                </template>
              </el-table-column>
              <el-table-column label="油箱容量"  prop="oliVolume" />
              <el-table-column label="生产厂家"  prop="dvcFct" :show-overflow-tooltip="true" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['base:car:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['base:car:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>


    <!-- 添加或修改车辆信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属组织/人" prop="deptId">
              <treeselect v-model="form.deptId" :options="enabledDeptOptions" :disable-branch-nodes="true" @select="optionSelected" :show-count="true" placeholder="请选择归属组织" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他类型" prop="otherType">
              <el-select v-model="form.otherType" placeholder="请选择其他类型">
                <el-option
                  v-for="dict in dict.type.dev_other_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="环保编号" prop="code">
              <el-input v-model="form.code" placeholder="请输入环保编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.otherType !== 2">
            <el-form-item label="车牌号" prop="carNo">
              <el-input v-model="form.carNo" placeholder="请输入车牌号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.otherType !== 2">
          <el-col :span="12">
            <el-form-item label="操作员" prop="driverId">
              <el-select v-model="form.driverId" @focus="getDriverOptions" @change="driverSelected" filterable placeholder="请选择操作员">
                <el-option
                  v-for="item in driverOptions"
                  :key="item.employeeId"
                  :label="item.name"
                  :value="item.employeeId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="油箱容量" prop="oliVolume">
              <el-input-number v-model="form.oliVolume" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="燃料类型" prop="fuelType">
              <el-select v-model="form.fuelType" placeholder="请选择燃料类型">
                <el-option
                  v-for="dict in dict.type.base_fuel_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆类型" prop="carType">
              <el-cascader
                ref="cascader"
                v-model="form.carType"
                :options="carTypeOptions"
                :props="{ value: 'id', label: 'label' }"
                @change="carTypeHandleChange"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-select v-model="form.carBrand" @focus="getBrandOptions" @change="brandSelected" filterable placeholder="请选择车辆品牌">
                <el-option
                  v-for="item in carBrandOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆型号" prop="carModel">
              <el-select v-model="form.carModel" @focus="getModelOptions" @change="modelSelected" filterable placeholder="请选择车辆型号">
                <el-option
                  v-for="item in carModelOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编号" prop="dvcNo">
              <el-input v-model="form.dvcNo" placeholder="请输入设备编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家" prop="dvcFct">
              <el-input v-model="form.dvcFct" placeholder="请输入设备制造厂家" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备出厂日期" prop="dvcDt">
              <el-date-picker clearable
                              v-model="form.dvcDt"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择设备出厂日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发动机型号" prop="engModel">
              <el-input v-model="form.engModel" placeholder="请输入发动机型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发动机编号" prop="engNo">
              <el-input v-model="form.engNo" placeholder="请输入发动机编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发动机制造厂家" prop="engFct">
              <el-input v-model="form.engFct" placeholder="请输入发动机制造厂家" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发动机出厂日期" prop="engDt">
              <el-date-picker clearable
                              v-model="form.engDt"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择发动机出厂日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发动机型式核准号" prop="engCheck">
              <el-input v-model="form.engCheck" placeholder="请输入发动机型式核准号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="额定功率" prop="power">
              <el-input v-model="form.power" placeholder="请输入额定功率" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="ownerContact">
              <el-input v-model="form.ownerContact" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照编号" prop="ownerIdentify">
              <el-input v-model="form.ownerIdentify" placeholder="请输入营业执照编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业地址" prop="ownerAddress">
              <el-input v-model="form.ownerAddress" placeholder="请输入企业地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所有企业/人详细地址" prop="ownerAddressDetail">
              <el-input v-model="form.ownerAddressDetail" placeholder="请输入所有企业/人详细地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作证编号" prop="driverCert">
              <el-input v-model="form.driverCert" placeholder="请输入操作证编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驾驶员联系方式" prop="driverContact">
              <el-input v-model="form.driverContact" placeholder="请输入驾驶员联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="办证机构" prop="certOrg">
              <el-input v-model="form.certOrg" placeholder="请输入办证机构" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作员身份证" prop="driverIdentify">
              <el-input v-model="form.driverIdentify" placeholder="请输入操作员身份证" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCar, getCar, delCar, addCar, updateCar, getDeptEmployees, carTypeTreeSelect, getCarBrandList, getCarModelList, deptTreeSelectThree } from "@/api/base/car";
import { deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";

export default {
  name: "Car",
  dicts: ['dev_other_type','base_fuel_type'],
  components: { Treeselect, Splitpanes, Pane },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车辆信息表格数据
      carList: [],
      // 弹出层标题
      title: "",
      // 组织名称
      deptName: undefined,
      // 所有组织树选项
      deptOptions: undefined,
      // 所有操作员选项
      driverOptions: undefined,
      // 所有组织树选项
      deptOptionsShow: undefined,
      // 过滤掉已禁用组织树选项
      enabledDeptOptions: undefined,
      carTypeOptions: undefined,
      carBrandOptions: undefined,
      carModelOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        carNo: null,
        code: null,
        carType: null,
        carBrand: null,
        carModel: null,
        otherType: null,
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: "归属组织ID不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "环保编号不能为空", trigger: "blur" }
        ],
        otherType: [
          { required: true, message: "其他类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选组织树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getCarTypeTree();
    this.getDeptTreeThree();
  },
  methods: {
    /** 查询车辆信息列表 */
    getList() {
      this.loading = true;
      listCar(this.queryParams).then(response => {
        this.carList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询组织下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
      });
    },
    getDeptTreeThree() {
      deptTreeSelectThree().then(response => {
        this.deptOptionsShow = response.data;
      });
    },
    /** 查询类型下拉树结构 */
    getCarTypeTree() {
      carTypeTreeSelect().then(response => {
        console.log(response.data);
        this.carTypeOptions = response.data;
      });
    },
    // 过滤禁用的组织
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false;
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children);
        }
        return true;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    optionSelected(d){
      this.form.deptName = d.label;
      this.form.ownerName = d.label;
      getDeptEmployees(d.id).then(response => {
        this.driverOptions = response.data;
      });
    },
    getDriverOptions(){
      if(!this.form.deptId){
        this.$message.error('请先选择组织');
      }
    },
    getBrandOptions(){
      if(!this.form.carType){
        this.$message.error('请先选择类型');
      }
    },
    getModelOptions(){
      if(!this.form.carBrand){
        this.$message.error('请先选择品牌');
      }
    },
    queryBrandOptions(){
      if(!this.queryParams.carType){
        this.$message.error('请先选择类型');
      }
    },
    queryModelOptions(){
      if(!this.queryParams.carBrand){
        this.$message.error('请先选择品牌');
      }
    },
    driverSelected(d){
      console.log(d);
      const item = this.driverOptions.find(option => option.employeeId === d);
      console.log(item);
      this.form.driverName = item.name;
      this.form.driverContact = item.contact;
      this.form.driverCert = item.certNo;
      this.form.driverIdentify = item.certificateNo;
      this.form.certOrg = item.certOrg;
    },
    brandSelected(b){
      console.log(b);
      const item = this.carBrandOptions.find(option => option.id === b);
      this.form.carBrand = item.id;
      console.log(item.name);
      this.form.carBrandName = item.name;
      getCarModelList(item.id).then(response => {
        console.log(response.data);
        this.carModelOptions = response.data;
      });
    },
    modelSelected(m){
      console.log(m);
      const item = this.carModelOptions.find(option => option.id === m);
      this.form.carModel = item.id;
      console.log(item.name);
      this.form.carModelName = item.name;
    },
    carTypeHandleChange(e){
      console.log(e);
      let nodesInfo = this.$refs['cascader'].getCheckedNodes();
      console.log(nodesInfo[0]);
      console.log(nodesInfo[0].value);
      console.log(nodesInfo[0].pathLabels.join('/'));
      this.form.carTypeName = nodesInfo[0].pathLabels.join('/');
      this.form.carType = nodesInfo[0].value;
      getCarBrandList(nodesInfo[0].value).then(response => {
        console.log(response.data);
        this.carBrandOptions = response.data;
      });
    },
    queryCarTypeHandleChange(e){
      let nodesInfo = this.$refs['cascader'].getCheckedNodes();
      console.log(nodesInfo[0]);
      console.log(nodesInfo[0].value);
      console.log(nodesInfo[0].pathLabels.join('/'));
      this.queryParams.carType = nodesInfo[0].value;
      getCarBrandList(nodesInfo[0].value).then(response => {
        this.carBrandOptions = response.data;
      });
    },
    queryBrandSelected(b){
      console.log(b);
      const item = this.carBrandOptions.find(option => option.id === b);
      this.queryParams.carBrand = item.id;
      getCarModelList(item.id).then(response => {
        console.log(response.data);
        this.carModelOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        carId: null,
        deptId: null,
        deptName: null,
        carNo: null,
        code: null,
        driverId: null,
        driverName: null,
        oliVolume: null,
        carType: null,
        carTypeName: null,
        carBrand: null,
        carBrandName: null,
        carModel: null,
        carModelName: null,
        otherType: null,
        dvcNo: null,
        dvcFct: null,
        dvcDt: null,
        engModel: null,
        engNo: null,
        engFct: null,
        engDt: null,
        engCheck: null,
        power: null,
        fuelType: null,
        ownerName: null,
        ownerContact: null,
        ownerIdentify: null,
        ownerAddress: null,
        ownerAddressDetail: null,
        driverCert: null,
        driverContact: null,
        certOrg: null,
        driverIdentify: null,
        driverLocation: null,
        driverLocDetail: null,
        cardStatus: null,
        online: null,
        lng: null,
        lat: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.carId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车辆信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const carId = row.carId || this.ids
      getCar(carId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改车辆信息";
      });
      getDeptEmployees(row.deptId).then(response => {
        this.driverOptions = response.data;
      });
      if(row.carType){
        getCarBrandList(row.carType).then(response => {
          this.carBrandOptions = response.data;
        });
      }
      if(row.carBrand){
        getCarModelList(row.carBrand).then(response => {
          this.carModelOptions = response.data;
        });
      }

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.carId != null) {
            updateCar(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCar(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const carIds = row.carId || this.ids;
      this.$modal.confirm('是否确认删除车辆信息编号为"' + carIds + '"的数据项？').then(function() {
        return delCar(carIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/car/export', {
        ...this.queryParams
      }, `car_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
